<?php
/*
Plugin Name: cos-html-cache
Plugin URI: http://www.storyday.com/tag/cos-html-cache
Description: cos-html-cache是一个非常高效的纯净态缓存插件
Version: 2.7.4
Author: jiangdong
date:2007-07-19
Author URI:http://www.storyday.com
*/

/* config */
define('IS_INDEX',true);// false = 不缓存首页

/*end of config*/

define('COSVERSION','2.7.4');

require_once(ABSPATH . 'wp-admin/includes/file.php');
/* end of config */

$cossithome = get_option('home');
$script_uri = rtrim( "https://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]  ,"/");//http协议需要改为网站协议
$home_path = get_home_path();

define('SCRIPT_URI',$script_uri);
define('CosSiteHome',$cossithome);
define('CosBlogPath', $home_path);
define("COSMETA","<!--本页面由云落于".date("Y-m-d H:i:s")." 手工缓存而来-->");
function CreateHtmlFile($FilePath,$Content){
	$FilePath = preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', $FilePath);

	// if there is http:// $FilePath will return its bas path
	$dir_array = explode("/",$FilePath);

	//split the FilePath
	$max_index = count($dir_array) ;
	$i = 0;
	$path = $_SERVER['DOCUMENT_ROOT']."/";

	while( $i < $max_index ){
		$path .= "/".$dir_array[$i];
		$path = str_replace("//","/",$path);

		if( $dir_array[$i] == "" ){
			$i ++ ;
			continue;
		}

		if( substr_count($path, '&') ) return true;
		if( substr_count($path, '?') ) return true;
		if( !substr_count($path, '.htm') ){
			//if is a directory
			if( !file_exists( $path ) ){
				@mkdir( $path, 0777);
				@chmod( $path, 0777 );
			}
		}
		$i ++;
	}

    if( is_dir( $path ) ){
		$path = $path."/index.html";
	}
	if ( !strstr( strtolower($Content), '</html>' ) ) return;

	//if sql error ignore...
	$fp = @fopen( $path , "w+" );
	if( $fp ){
		@chmod($path, 0666 ) ;
		@flock($fp ,LOCK_EX );

		// write the file。
		fwrite( $fp , $Content );
		@flock($fp, LOCK_UN);
		fclose($fp);
	 }
}

/* read the content from output buffer */
$is_buffer = false;
if( substr_count($_SERVER['REQUEST_URI'], '.htm') || ( SCRIPT_URI == CosSiteHome) ){
	if( strlen( $_COOKIE['wordpress_logged_in_'.COOKIEHASH] ) < 4 ){
		$is_buffer = true;
	}
	if(  substr_count($_SERVER['REQUEST_URI'], '?'))  $is_buffer = false;
	if(  substr_count($_SERVER['REQUEST_URI'], '../'))  $is_buffer = false;
}

if( $is_buffer ){
	ob_start('cos_cache_ob_callback');
	register_shutdown_function('cos_cache_shutdown_callback');
}

function cos_cache_ob_callback($buffer){

	$buffer = preg_replace('/(<\s*input[^>]+?(name=["\']author[\'"])[^>]+?value=(["\']))([^"\']+?)\3/i', '\1\3', $buffer);

	$buffer = preg_replace('/(<\s*input[^>]+?value=)([\'"])[^\'"]+\2([^>]+?name=[\'"]author[\'"])/i', '\1""\3', $buffer);

	$buffer = preg_replace('/(<\s*input[^>]+?(name=["\']url[\'"])[^>]+?value=(["\']))([^"\']+?)\3/i', '\1\3', $buffer);

	$buffer = preg_replace('/(<\s*input[^>]+?value=)([\'"])[^\'"]+\2([^>]+?name=[\'"]url[\'"])/i', '\1""\3', $buffer);

	$buffer = preg_replace('/(<\s*input[^>]+?(name=["\']email[\'"])[^>]+?value=(["\']))([^"\']+?)\3/i', '\1\3', $buffer);

	$buffer = preg_replace('/(<\s*input[^>]+?value=)([\'"])[^\'"]+\2([^>]+?name=[\'"]email[\'"])/i', '\1""\3', $buffer);

	if( !substr_count($buffer, '<!--cos-html-cache-safe-tag-->') || substr_count($buffer, '<!--no-cache-->') > 0) return  $buffer;

	global $post;
	if( has_shortcode( $post->post_content, 'secret') || has_shortcode( $post->post_content, 'reply') || has_shortcode( $post->post_content, 'pay') ) return  $buffer;

	if( substr_count($buffer, 'post_password') > 0 ) return  $buffer;//to check if post password protected
	$wppasscookie = "wp-postpass_".COOKIEHASH;
	if( strlen( $_COOKIE[$wppasscookie] ) > 0 ) return  $buffer;//to check if post password protected
	/*
	$comment_author_url='';
$comment_author_email='';
$comment_author='';*/


	elseif( SCRIPT_URI == CosSiteHome) {// creat homepage
		$fp = @fopen( CosBlogPath."index.bak" , "w+" );
		if( $fp ){
			@flock($fp ,LOCK_EX );
			// write the file。
			fwrite( $fp , $buffer.COSMETA );
			@flock($fp, LOCK_UN);
			fclose($fp);
		 }
		if(IS_INDEX)
			@rename(CosBlogPath."index.bak",CosBlogPath."index.html");
	}
	else
		CreateHtmlFile($_SERVER['REQUEST_URI'],$buffer.COSMETA );
	return $buffer;
}

function cos_cache_shutdown_callback(){
	ob_end_flush();
	flush();
}

if( !function_exists('DelCacheByUrl') ){
	function DelCacheByUrl($url) {
		$url = CosBlogPath.str_replace( CosSiteHome,"",$url );
		$url = str_replace("//","/", $url );
		 if( file_exists( $url )){
			 if( is_dir( $url )) {@unlink( $url."/index.html" );@rmdir($url);}
			 else @unlink( $url );
		 }
	}
}

if( !function_exists('htmlCacheDel') ){
	// 删除单页缓存
	function htmlCacheDel($post_ID) {
		if( $post_ID == "" ) return true;
		$uri = get_permalink($post_ID);
		DelCacheByUrl($uri );
	}
}

if( !function_exists('htmlCacheDelNb') ){
	// 删除相邻文章缓存
	function htmlCacheDelNb($post_ID) {
		if( $post_ID == "" ) return true;
		$uri = get_permalink($post_ID);
		DelCacheByUrl($uri );
		global $wpdb;
		$postRes=$wpdb->get_results("SELECT `ID`  FROM `" . $wpdb->posts . "` WHERE post_status = 'publish'   AND   post_type='post'   AND  ID < ".$post_ID." ORDER BY ID DESC LIMIT 0,1;");
		$uri1 = get_permalink($postRes[0]->ID);
		DelCacheByUrl($uri1 );
		$postRes=$wpdb->get_results("SELECT `ID`  FROM `" . $wpdb->posts . "` WHERE post_status = 'publish'  AND   post_type='post'    AND ID > ".$post_ID."  ORDER BY ID ASC  LIMIT 0,1;");
		if( $postRes[0]->ID != '' ){
			  $uri2  = get_permalink($postRes[0]->ID);
			  DelCacheByUrl($uri2 );
		}

	}
}

//创建首页缓存
if( !function_exists('createIndexHTML') ){
	function createIndexHTML($post_ID){
		if( $post_ID == "" ) return true;
		//[menghao]@rename(ABSPATH."index.html",ABSPATH."index.bak");
		@rename(CosBlogPath."index.html",CosBlogPath."index.bak");//[menghao]
	}
}

if(!function_exists("htmlCacheDel_reg_admin")) {
	/**
	* Add the options page in the admin menu
	*/
	function htmlCacheDel_reg_admin() {
		if (function_exists('add_options_page')) {
			add_options_page('html-cache-creator', '静态缓存',8, basename(__FILE__), 'cosHtmlOption');
			//add_options_page($page_title, $menu_title, $access_level, $file).
		}
	}
}

add_action('admin_menu', 'htmlCacheDel_reg_admin');

if(!function_exists("cosHtmlOption")) {
function cosHtmlOption(){
	do_cos_html_cache_action();
?>
	<div class="wrap" style="padding:10px 0 0 10px;text-align:left">
	<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
	<p>
	点击下面的按钮删除所有的html文件缓存</p>
	<p>说明：这仅仅是删除缓存文件，不会真正从数据库中删除你的文章</p>
	<p>如果你想更新缓存，你必须点下面的按钮删除所有的缓存，对应文章的缓存将会在接下来的第一次被访问的时候被创建</p>

	<p><b>删除指定文章的缓存(请输入ID号或者部分标题)</b> <input type="text" id="cache_id" name="cache_id" value="" /> 想删除所有缓存这里请留空</p>
	<p><input type="submit" value="删除HTML文件缓存" id="htmlCacheDelbt" name="htmlCacheDelbt" onClick="return checkcacheinput(); " />
	</form>
	</div>
	<SCRIPT LANGUAGE="JavaScript">
		function checkcacheinput(){
		document.getElementById('htmlCacheDelbt').value = '请稍后...';
		return true;
	}
	</SCRIPT>
<?php
	}
}
/*
end of get url
*/
// deal with rebuild or delete
function do_cos_html_cache_action(){
	if( !empty($_POST['htmlCacheDelbt']) ){
		@rename(CosBlogPath."index.html",CosBlogPath."index.bak");
		@chmod( CosBlogPath."index.bak", 0666 );
		global $wpdb;
		if( intval($_POST['cache_id']) * 1 > 0 ){
			//delete cache by id
			 DelCacheByUrl(get_permalink($_POST['cache_id']));
			 $msg = __('指定的缓存被成功删除: ID=','cosbeta').$_POST['cache_id'];

		}else if( strlen($_POST['cache_id']) > 2  ){
			$postRes=$wpdb->get_results("SELECT `ID`  FROM `" . $wpdb->posts . "` WHERE post_title like '%".$_POST['cache_id']."%' LIMIT 0,1 ");
			DelCacheByUrl( get_permalink( $postRes[0]->ID ) );
			$msg = __('指定的缓存被成功删除: 标题=','cosbeta').$_POST['cache_id'];
		}
		else{
		$postRes=$wpdb->get_results("SELECT `ID`  FROM `" . $wpdb->posts . "` WHERE post_status = 'publish' AND ( post_type='post' OR  post_type='page' )  ORDER BY post_modified DESC ");
		foreach($postRes as $post) {
			DelCacheByUrl(get_permalink($post->ID));
			}
			$msg = __('HTML文件缓存已经成功删除','cosbeta');
		}
	}
	if($msg)
	echo '<div class="updated"><strong><p>'.$msg.'</p></strong></div>';
}
$is_add_comment_is = true;
/*
 * with ajax comments
 */
if ( !function_exists("cos_comments_js") ){
	function cos_comments_js($postID){
		global $is_add_comment_is;
		if( $is_add_comment_is ){
			$is_add_comment_is = false;
		?>
		<script type="text/javascript" src="<?php echo plugin_dir_url(__FILE__ );?>common.js.php?hash=<?php echo COOKIEHASH;?>"></script>
		<script type="text/javascript">
		var hash = "<?php echo COOKIEHASH;?>";
		var author_cookie = "comment_author_" + hash;
		var email_cookie = "comment_author_email_" + hash;
		var url_cookie = "comment_author_url_" + hash;
		var adminmail = "<?php  echo str_replace('@','{_}',get_option('admin_email'));?>";
		var adminurl = "<?php  echo  get_option('siteurl') ;?>";
		setCommForm();
		</script>
	<?php
		}
	}
}

function CosSafeTag(){
	if   ( is_single() || (is_home() && IS_INDEX) )  {
		echo "<!--cos-html-cache-safe-tag-->";
	}
}
function clearCommentHistory(){
global $comment_author_url,$comment_author_email,$comment_author;
$comment_author_url='';
$comment_author_email='';
$comment_author='';
}
//add_action('comments_array','clearCommentHistory');
add_action('get_footer', 'CosSafeTag');
add_action('comment_form', 'cos_comments_js');

/* end of ajaxcomments*/
if(IS_INDEX){
add_action('publish_post', 'createIndexHTML');
add_action('delete_post', 'createIndexHTML');
add_action('edit_post', 'createIndexHTML');
}

add_action('publish_post', 'htmlCacheDelNb');
add_action('delete_post', 'htmlCacheDelNb');
add_action('edit_post', 'htmlCacheDel');
add_action('comment_post','htmlCacheDel');
?>